package com.xc.freeapp.service.impl;

import java.util.Date;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xc.freeapp.dao.UsersDao;
import com.xc.freeapp.dao.dataSource.DBContextHolder;
import com.xc.freeapp.entity.Users;
import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.redis.VerificationCodeDao;
import com.xc.freeapp.service.RegisteredService;
import com.xc.freeapp.util.Constant;
import com.xc.freeapp.util.DateUtils;
import com.xc.freeapp.util.SendSMSUtil;
import com.xc.freeapp.utils.enums.SMSTemplateCode;

/**
 * 
 * @author GuoShuaipeng
 * 
 */
@Service
public class RegisteredServiceImpl implements RegisteredService {
	private Logger log = LoggerFactory.getLogger(RegisteredServiceImpl.class);

	@Autowired
	private UsersDao usersdao;
	@Autowired
	VerificationCodeDao verificationCodeDaoImpl;

	public String getVerificationCode(Map<String, String> map) throws Exception {
		DBContextHolder.switchDataSourceRW();// 切换数据源
		String telephone = map.get("telephone");
		String verCode = getVerCode();
		log.info(telephone + "调用接口发送验证码开始");
		String[] verCodeArray = { verCode };

		try {
			SendSMSUtil.sendCode(telephone, verCodeArray, SMSTemplateCode.YAN_ZHENG_MA);
		}catch (BaseException e) {
			log.error(telephone + ":发送验证码短信失败");
			throw e;
		} catch (Exception e) {
			log.error(telephone + ":发送验证码短信失败");
			
		}
		log.info(telephone + "开始入redis：verCode=" + verCode);

		boolean status = true;
		try {
			status = verificationCodeDaoImpl.put(telephone, verCode);
		} catch (Exception e) {
			log.error("验证码入redis出错");
			throw new BaseException("999", "验证码入redis出错");
		}

		if (Boolean.FALSE == status) {
			throw new BaseException("999", "验证码入redis出错");
		}
		return verCode;
	}
	
	

	private String getVerCode() {
		Random random = new Random();
		String verCode = (random.nextInt(9)+1)+"";
		for (int i = 0; i < 5; i++) {
			verCode = verCode + random.nextInt(10);
		}
	
		return verCode;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public boolean register(Map<String, String> map) throws Exception {
		DBContextHolder.switchDataSourceRW();// 切换数据源
		String verificationCode = map.get("verificationCode");
		String telephone = map.get("telephone");
		String verCode = verificationCodeDaoImpl.get(telephone);
		if (verCode == null) {
			throw new BaseException(Constant.ERRORCODE_151, "验证码错误");
		}
		if (!verCode.equals(verificationCode)) {
			throw new BaseException(Constant.ERRORCODE_151, "验证码错误");
		}
		Users users = new Users();
		users.setBusinessid(Integer.valueOf(map.get("appId")));
		users.setRegistrationid(map.get("registrationId"));
		users.setTelephone(map.get("telephone"));
		users.setRealName(map.get("telephone"));
		users.setLoginpwd(map.get("loginPwd"));
		users.setLoginname(map.get("telephone"));
		Date date = DateUtils.getDate();
		users.setCreatetime(date);
		users.setUpdatetime(date);
		users.setDelflag("t");
		users.setDeviceinfo(map.get("deviceinfo"));
		if ("android".equals(map.get("registerType"))) {
			users.setRegistertype("1");
		}
		if ("ios".equals(map.get("registerType"))) {
			users.setRegistertype("2");
		}
		try {
			int insertcount = usersdao.save(users);
		} catch (org.springframework.dao.DuplicateKeyException e) {
			throw new BaseException(Constant.ERRORCODE_114, "手机号已经存在!");
		} catch (Exception e) {
			throw new BaseException(Constant.COMMON_ERROR, "插入数据出错!");
		}
		return Boolean.TRUE;
	}

	/**
	 * 重置密码接口
	 */

	@Transactional(propagation = Propagation.REQUIRED)
	public boolean resetLoginwd(Map<String, String> map) throws BaseException {
		DBContextHolder.switchDataSourceRW();// 切换数据源
		try {
			int businessid = Integer.parseInt(map.get("businessId"));
			String telephone = map.get("telephone");
			String newloginpw = map.get("newloginpw");
			String verificationCode = map.get("verificationCode");
			String verCode = verificationCodeDaoImpl.get(telephone);
			log.info("redis中验证码为verCode=" + verCode);
			if (verCode == null) {
				throw new BaseException("151", "验证码错误");
			}
			if (!verCode.equals(verificationCode)) {
				throw new BaseException("151", "验证码错误");
			}
			int i = usersdao.updateByTelephone(businessid, telephone,
					newloginpw);
			if (i < 1) {
				throw new BaseException(Constant.ERRORCODE_555);
			}
		} catch (BaseException e) {
			log.error("验证码错误");
			throw e;
		} catch (Exception e) {
			log.error("重置密码接口系统异常{}",e.getMessage());
			throw new BaseException("900");
		}
		return true;
	}
}
